package com
{
	import com.logs;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.system.Security;
	import flash.text.TextField;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class TestSocket extends Sprite
	{
		public var data:String;
		
		public function TestSocket(msg:String = null)
		{
			new logs();
			addChild(logs.txt);
			//if(msg==null)msg = "writefile&a.c&fuck&" + "fuck".length;
			if (msg == null)
				msg = "poweroff";
			var socket:CustomSocket = new CustomSocket("localhost", 8843);
			socket.send(msg);
			socket.addEventListener(Event.COMPLETE, traces);
		}
		
		private function traces(e:Event):void
		{
			data = e.target.data;
			logs.adds("receive:", data);
			//showHtml(data);
			dispatchEvent(e);
		}
		
		private var txt:TextField = new TextField();
		
		private function showHtml(str:String):void
		{
			addChild(txt);
			txt.htmlText = str;
			txt.width = stage.stageWidth;
			txt.height = stage.stageHeight;
		}
	}
}

import com.logs;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;

class CustomSocket extends Socket
{
	public var data:String = null;
	
	private var sendData:String = null;
	private var host:String;
	private var port:uint;
	
	public function CustomSocket(host:String = null, port:uint = 0)
	{
		this.port = port;
		this.host = host;
		configureListeners();
	}
	
	public function send(sendData:String):void
	{
		this.sendData = sendData;
		if (host && port)
		{
			super.connect(host, port);
		}
	}
	
	private function configureListeners():void
	{
		addEventListener(Event.CONNECT, connectedh);
		addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		
		addEventListener(IOErrorEvent.IO_ERROR, Handler);
		addEventListener(SecurityErrorEvent.SECURITY_ERROR, Handler);
		addEventListener(Event.CLOSE, Handler);
	}
	
	private function connectedh(e:Event):void
	{
		logs.adds("sendRequest:" + sendData);
		writeUTFBytes(sendData);
		flush();
	}
	
	private function Handler(e:Event):void
	{
		logs.adds("Handler: " + e);
		dispatchEvent(new Event(Event.COMPLETE));
		if (connected)
			close();
	}
	
	private function socketDataHandler(event:ProgressEvent):void
	{
		//data = readMultiByte(bytesAvailable, "utf-8");
		data = readMultiByte(bytesAvailable, "gbk");
		dispatchEvent(new Event(Event.COMPLETE));
		if (connected)
			close();
	}
}
